package com.alm.web.controller.alm.getwayinfo;

import com.alibaba.fastjson.JSON;
import com.alm.common.core.controller.BaseController;
import com.alm.common.core.domain.AjaxResult;
import com.alm.common.core.page.TableDataInfo;
import com.alm.common.core.redis.RedisCache;
import com.alm.common.utils.SecurityUtils;
import com.alm.entity.SetMacMgModel;
import com.alm.handle.core.domain.entity.SysAlmEventsLog;
import com.alm.handle.core.domain.entity.rq.GetWayInfoRq;
import com.alm.handle.core.domain.entity.rq.JdqControlsRq;
import com.alm.handle.core.domain.entity.rs.GetWayUpEleDataRS;
import com.alm.handle.service.AlmGetWayDevCurrentDataService;
import com.alm.handle.service.SysAlmEventsLogService;
import com.alm.handle.util.SendMessage;
import com.alm.handle.util.SoketEleKey;
import com.alm.service.PasGetWayNetWorkService;
import com.alm.service.SendGetWayNetWorkService;
import com.alm.util.ByteUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.alm.common.utils.PageUtils.startPage;

@RestController
@RequestMapping("/alm/dev/getwayupload")
@Valid
public class GetWayUploadDevDataController extends BaseController {
    @Autowired
    private SysAlmEventsLogService eventsLogService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private AlmGetWayDevCurrentDataService getWayDevCurrentDataService;
    @Autowired
    private SendGetWayNetWorkService getWayNetWorkService;
    /**
     * 对网关上报的数据进行分页展示查询
     * @param gwMac
     * @param pageNum
     * @param pageSize
     * @return
     */
    @PostMapping("/uploadList")
    public TableDataInfo list(String  gwMac,Integer pageNum,Integer pageSize) {
        String sort_key= SoketEleKey.GW_ELE_ZSET+gwMac; // 使用zeset value是更新时间   越靠近前面能被查询到
        String data_key= SoketEleKey.GW_ELE_DATA+gwMac; // 实际数据
        List<GetWayUpEleDataRS> getWayUpEleDataRS=new ArrayList<>();
        pageNum=pageNum==null?1:pageNum;
        pageSize=pageSize==null?10:pageSize;
        //  对redis的数据进行分页查询
        Long total=redisCache.countZset(sort_key);
        if(total>0){
            // 取出数据并且进行分页
            Integer index=pageNum*pageSize;
            Long start=total-index;
            if(start<0l){
                start=0l;
            }
            Set<Object> sort_mac=redisCache.rangeZset(sort_key,start,(total-index+pageSize)-1);
            for(Object key:sort_mac){
                String data=redisCache.getCacheMapValue(data_key,(String) key);
                GetWayUpEleDataRS dataRS= JSON.parseObject(data,GetWayUpEleDataRS.class);
                dataRS.setDevId((String)key);
                getWayUpEleDataRS.add(dataRS);
            }
            return getDataTable(getWayUpEleDataRS, total);
        }
        return new TableDataInfo();
    }

    @PostMapping("/gwList")
    public TableDataInfo list(GetWayInfoRq getWayInfoRq) {
         getWayInfoRq.setCommpayId(SecurityUtils.getDeptId());
         getWayInfoRq.setIsAdmin(SecurityUtils.isAdmin(SecurityUtils.getUserId()));
        return getDataTable(getWayDevCurrentDataService.queryListByRq(getWayInfoRq));
    }

    /**
     * 操作继电器开关
     * @param jdqControlsRq
     * @return
     */
    @PostMapping("/snedJdqControls")
    public AjaxResult list(@RequestBody JdqControlsRq jdqControlsRq) {
        if(jdqControlsRq.getLineIdList()==null||jdqControlsRq.getLineIdList().size()==0){
            return error("请选择操作行数！");
        }
        Boolean bo=getWayDevCurrentDataService.sendJdqControlsRq(jdqControlsRq);
        if(bo){
            return success(1);
        }
        return error("发送失败，设备可能不在线或者其他错误！");
    }
    @PostMapping("/sendsetShowGWfilterDigAjax")
    public AjaxResult sendsetShowGWfilterDigAjax(@RequestBody SetMacMgModel setMacMgModel) {
        try {
            setMacMgModel.setDevType((short) 0x80);
            byte [] bytes=  getWayNetWorkService.sendFiltration(setMacMgModel);
            if(bytes == null || bytes.length == 0) {
                return error("生成的过滤条件数据为空");
            }
            logger.info("data: {}", ByteUtils.bytesToString(bytes));
            Boolean bo= SendMessage.sendMessage(bytes, setMacMgModel.getDeviceId().toUpperCase());
            if(bo){
                return success(1);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error("发送失败，设备可能不在线或者其他错误");
        }
        return error("发送失败");
    }

}
